<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="单据号" prop="purchasePlanNo">
        <el-input v-model="queryParams.purchasePlanNo" placeholder="请输入单据号" clearable size="small"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="申请人" prop="applyUser">
        <el-select v-model="queryParams.applyUser" placeholder="请选择申请人" clearable filterable size="small">
          <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请日期">
        <el-date-picker v-model="daterangeApplyTime" size="small" style="width: 240px" value-format="YYYY-MM-DD"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="申请状态" prop="applyStatus">
        <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态" clearable filterable size="small">
          <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="auditUser">
        <el-select v-model="queryParams.auditUser" placeholder="请选择审核人" clearable filterable size="small">
          <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核日期">
        <el-date-picker v-model="daterangeAuditTime" size="small" style="width: 240px" value-format="YYYY-MM-DD"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态：" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable size="small">
          <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="单据号" align="center" prop="purchasePlanNo" />
      <el-table-column label="申请人" align="center" prop="applyUser" :formatter="applyUserFormat" />
      <el-table-column label="申请日期" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="applyStatus" :formatter="applyStatusFormat" />
      <el-table-column label="审核人" align="center" prop="auditUser" :formatter="auditUserFormat" />
      <el-table-column label="审核日期" align="center" prop="auditTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.auditTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改采购计划对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px" :inline="true">
        <el-form-item label="单据号" prop="purchasePlanNo">
          <el-input v-model="form.purchasePlanNo" placeholder="请输入单据号" disabled />
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-select v-model="form.applyUser" placeholder="" clearable filterable disabled>
            <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期" prop="applyTime">
          <el-date-picker clearable size="small" v-model="form.applyTime" type="date" value-format="YYYY-MM-DD"
            placeholder="" disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="form.applyStatus" placeholder="" clearable filterable disabled>
            <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUser">
          <el-select v-model="form.auditUser" placeholder="请选择审核人" clearable filterable disabled>
            <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核日期" prop="auditTime">
          <el-date-picker clearable size="small" v-model="form.auditTime" type="date" value-format="YYYY-MM-DD"
            placeholder="选择审核日期" disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="form.auditStatus" placeholder="" clearable filterable disabled>
            <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="form.auditComment" type="textarea" placeholder="请输入审核意见" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" disabled />
        </el-form-item>
        <el-divider content-position="center">采购计划详细信息</el-divider>
        <el-table :data="scmPurchasePlanDetailList" :row-class-name="rowScmPurchasePlanDetailIndex"
          ref="scmPurchasePlanDetailRef">
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="物料" prop="materialName" width="300"></el-table-column>
          <el-table-column label="型号" prop="materialModel"></el-table-column>
          <el-table-column label="规格" prop="materialSpecification"></el-table-column>
          <el-table-column label="单位" prop="materialUnit"></el-table-column>
          <el-table-column label="采购数量" prop="quantity" width="150"></el-table-column>
          <el-table-column label="需求数量" prop="requireQuantity" width="150"></el-table-column>
          <el-table-column label="需求日期" prop="requireDate" width="240"></el-table-column>
          <el-table-column label="备注" prop="detailRemark" width="150"></el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="form.applyStatus!='2'" type="primary" @click="submitForm('1')">通 过</el-button>
          <el-button type="danger" @click="submitForm('0')">驳 回</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Search, Refresh, Edit } from '@element-plus/icons-vue'
import { listPlan4Audit, getPlan, auditPlan } from "@/api/purchase/plan"
import { ElMessage } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { getDicts } from '@/api/system/dict/data'
import { selectDictLabel } from '@/utils/ruoyi'

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 子表选中数据
const checkedScmPurchasePlanDetail = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 采购计划表格数据
const planList = ref([])
// 采购计划详细表格数据
const scmPurchasePlanDetailList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 申请人字典
const applyUserOptions = ref([])
// 申请时间时间范围
const daterangeApplyTime = ref([])
// 申请状态：0未提交1待审核字典
const applyStatusOptions = ref([])
// 审核人字典
const auditUserOptions = ref([])
// 审核日期时间范围
const daterangeAuditTime = ref([])
// 审核状态：0审核未通过1审核通过字典
const auditStatusOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  purchasePlanNo: null,
  applyUser: null,
  applyTime: null,
  applyStatus: null,
  auditUser: null,
  auditTime: null,
  auditStatus: null,
  orderByColumn: 'apply_time',
  isAsc: 'desc',
})

// 表单参数
const form = reactive({
  id: null,
  purchasePlanNo: null,
  applyUser: null,
  applyTime: null,
  applyStatus: null,
  auditUser: null,
  auditTime: null,
  auditStatus: null,
  auditComment: null,
  remark: null,
  scmPurchasePlanDetailList: [],
})

// 表单校验
const checkAuditComment = (rule, value, callback) => {
  if (form.auditStatus == '0') {
    if (!value) {
      callback(new Error('请输入审核意见'))
    }
  }
  callback()
}

const rules = {
  auditComment: [{
    validator: checkAuditComment,
    trigger: 'blur'
  }]
}

const formRef = ref(null)
const queryFormRef = ref(null)
const scmPurchasePlanDetailRef = ref(null)

// 监听采购计划详细列表变化
watch(scmPurchasePlanDetailList, (newVal) => {
  form.scmPurchasePlanDetailList = newVal
}, { deep: true, immediate: true })

/** 查询采购计划列表 */
const getList = async () => {
  loading.value = true
  queryParams.params = {}
  if (daterangeApplyTime.value && daterangeApplyTime.value.length > 0) {
    queryParams.params["beginApplyTime"] = daterangeApplyTime.value[0]
    queryParams.params["endApplyTime"] = daterangeApplyTime.value[1]
  }
  if (daterangeAuditTime.value && daterangeAuditTime.value.length > 0) {
    queryParams.params["beginAuditTime"] = daterangeAuditTime.value[0]
    queryParams.params["endAuditTime"] = daterangeAuditTime.value[1]
  }
  try {
    const response = await listPlan4Audit(queryParams)
    planList.value = response.rows
    total.value = response.total
  } finally {
    loading.value = false
  }
}

// 申请人字典翻译
const applyUserFormat = (row) => {
  return selectDictLabel(applyUserOptions.value, row.applyUser)
}

// 申请状态字典翻译
const applyStatusFormat = (row) => {
  return selectDictLabel(applyStatusOptions.value, row.applyStatus)
}

// 审核人字典翻译
const auditUserFormat = (row) => {
  return selectDictLabel(auditUserOptions.value, row.auditUser)
}

// 审核状态字典翻译
const auditStatusFormat = (row) => {
  return selectDictLabel(auditStatusOptions.value, row.auditStatus)
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: null,
    purchasePlanNo: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    auditComment: null,
    remark: null,
    scmPurchasePlanDetailList: [],
  })
  scmPurchasePlanDetailList.value = []
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  daterangeApplyTime.value = []
  daterangeAuditTime.value = []
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset()
  const id = row.id || ids.value
  try {
    const response = await getPlan(id)
    Object.assign(form, response.data)
    scmPurchasePlanDetailList.value = response.data.scmPurchasePlanDetailList
    open.value = true
    title.value = "审核采购计划"
  } catch (error) {
    console.error('获取采购计划详情失败:', error)
  }
}

//审核按钮
const submitForm = async (status) => {
  form.auditStatus = status
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    await auditPlan(form)
    ElMessage.success("审核成功")
    open.value = false
    getList()
  } catch (error) {
    console.error('审核失败:', error)
  }
}

/** 采购计划详细序号 */
const rowScmPurchasePlanDetailIndex = ({ row, rowIndex }) => {
  row.index = rowIndex + 1
}

// 初始化
onMounted(async () => {
  await getList()
  try {
    // 获取字典数据
    const [applyStatusRes, auditStatusRes] = await Promise.all([
      getDicts("apply_status"),
      getDicts("audit_status")
    ])

    // 获取用户数据
    const userRes = await getDicts("sys_user")
    
    applyUserOptions.value = userRes.data
    applyStatusOptions.value = applyStatusRes.data
    auditUserOptions.value = userRes.data
    auditStatusOptions.value = auditStatusRes.data
  } catch (error) {
    console.error('获取字典数据失败:', error)
  }
})
</script> 